package xyz.molzhao.plugin.autoconfigure;

import com.baomidou.dynamic.datasource.plugin.MasterSlaveAutoRoutingPlugin;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import xyz.molzhao.plugin.crypt.EncryptInterceptor;
import xyz.molzhao.plugin.properties.MybatisPluginConstant;
import xyz.molzhao.plugin.properties.MybatisPluginProperties;

@Configuration
@EnableTransactionManagement
@EnableConfigurationProperties({MybatisPluginProperties.class})
@ConditionalOnProperty(prefix = MybatisPluginConstant.MYBATIS_PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class MybatisPluginAutoConfiguration {
    private final MybatisPluginProperties properties;

    public MybatisPluginAutoConfiguration(MybatisPluginProperties properties) {
        this.properties = properties;
    }

    // 读写分离组件
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = MybatisPluginConstant.MYBATIS_PREFIX, name = MybatisPluginConstant.MYBATIS_MASTER_SLAVE_AUTO_ROUTING, havingValue = "true")
    public MasterSlaveAutoRoutingPlugin masterSlaveAutoRoutingPlugin() {
        return new MasterSlaveAutoRoutingPlugin();
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = MybatisPluginConstant.MYBATIS_PREFIX, name = MybatisPluginConstant.MYBATIS_ENCRYPT_PLUGIN_ENABLE, havingValue = "true")
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> {
            //插件拦截链采用了责任链模式，执行顺序和加入连接链的顺序有关
            EncryptInterceptor myPlugin = new EncryptInterceptor(properties);
            //设置参数，比如阈值等，可以在配置文件中配置，这里直接写死便于测试
            configuration.addInterceptor(myPlugin);
        };
    }
}
